// SocketConsole.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "CopySocket.h"

int EnumSocket( )
{
	int iRet;
	iSocketCount=0;
	WSADATA wsaData;
	iRet = WSAStartup( MAKEWORD(1,1), &wsaData );
	if ( iRet )
		printf( "WSAStartup Error:%d\n", GetLastError() );

	DWORD currentProcessId=GetCurrentProcessId();
	HMODULE hNtdll = NULL;

	hNtdll = LoadLibrary( L"ntdll.dll" );
	if ( !hNtdll )
	{
		printf( "LoadLibrary( NTDLL.DLL ) Error:%d\n", GetLastError() );
		return false;
	}

	NtQuerySystemInformation = (NTQUERYSYSTEMINFORMATION)GetProcAddress(hNtdll,"NtQuerySystemInformation");
	if ( !NtQuerySystemInformation )
	{
		printf( "GetProcess( NtQuerySystemInformation ) Error:%d\n", GetLastError() );
		return false;
	}

	DWORD dwNumBytes = MAX_HANDLE_LIST_BUF;
	PDWORD pdwHandleList = (PDWORD)malloc( dwNumBytes );
	if ( !pdwHandleList )
	{
		printf( "Malloc for Handle List Error:%d\n", GetLastError() );
		return false;
	}

	DWORD dwNumBytesRet = 0;
	iRet = (*NtQuerySystemInformation)(NT_HANDLE_LIST,pdwHandleList,dwNumBytes,&dwNumBytesRet);
	DWORD dwNumEntries;
	PHANDLEINFO pHandleInfo;
	if ( iRet )
	{
		printf( "NtQuerySystemInformation return %d, Error:%d\n",dwNumBytesRet,GetLastError() );
	}
	else
	{
		HANDLE hProc;
		dwNumEntries = pdwHandleList[0];
		pHandleInfo = (PHANDLEINFO)( pdwHandleList + 1 );

		for ( DWORD i = 0; i < dwNumEntries; i++ )
		{
			if ((pHandleInfo->ObjType == OBJECT_TYPE_SOCKET ) && ( pHandleInfo->dwPid == currentProcessId ) )
			{

				sockaddr_in name = {0}; 
				name.sin_family = AF_INET; 
				int namelen = sizeof(sockaddr_in); 
				SOCKET s = (SOCKET)(HANDLE)pHandleInfo->HndlOffset;

				iRet = getsockname( s, (sockaddr*)&name, &namelen ); 

				if ( iRet != SOCKET_ERROR ) 
				{ 
					int sockType = 0; 
					int optlen = 4; 
					iRet = getsockopt(    s, 
						SOL_SOCKET, 
						SO_TYPE, 
						(char*)&sockType, 
						&optlen ); 
					printf( "PID=%4d PORT=%5d %s\n", pHandleInfo->dwPid, ntohs( name.sin_port ), szSockType[sockType] ); 
				} 

			}
			pHandleInfo++;
		}
	}
	if ( pdwHandleList )
		free( pdwHandleList );
	FreeLibrary(hNtdll);

	return 0;
}
